package com.wg.user.util;

import com.alibaba.fastjson.JSON;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.tomcat.util.codec.binary.Base64;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Date;

public class MyJwt {

    private String id = "user";

    private String name = "jwt";

    private String key = "wg1199.2046mvZd1o0";

    private long expired = 1024L * 24L * 60L * 60L * 1000L;

    public String getId() {
        return this.id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return this.name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getKey() {
        return this.key;
    }

    public void setKey(String key) {
        this.key = key;
    }

    public long getExpired() {
        return this.expired;
    }

    public void setExpired(long expired) {
        this.expired = expired;
    }

    public SecretKey generateSecretKey() {
        byte[] encodedKey = Base64.decodeBase64(this.key);
        SecretKey secretKey = new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
        return secretKey;
    }

    public String generateJwt(String subject) throws Exception {
        return this.createJwt(subject);
    }

    public String generateJwt(Object subject) throws Exception {
        return this.createJwt(JSON.toJSONString(subject));
    }

    private String createJwt(String subject) throws Exception {
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        long nowMs = System.currentTimeMillis();
        Date now = new Date(nowMs);
        SecretKey secretKey = this.generateSecretKey();

        JwtBuilder builder = Jwts.builder().setId(this.id)
                .setIssuedAt(now)
                .setSubject(subject)
                .signWith(signatureAlgorithm, secretKey);

        long expiredMs = nowMs + this.expired;
        Date expireDate = new Date(expiredMs);
        builder.setExpiration(expireDate);

        return builder.compact();
    }

    public Claims parseJwt(String jwt) throws Exception {
        SecretKey secretKey = this.generateSecretKey();
        return Jwts.parser().setSigningKey(secretKey)
                .parseClaimsJws(jwt)
                .getBody();
    }
}
